package com.qf.shop.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.shop.entity.Manager;
import com.qf.shop.service.ManagerService;
import com.qf.shop.service.impl.ManagerServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

@WebServlet( "/login")
public class LoginManagerController extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletInputStream inputStream = request.getInputStream();
        ObjectMapper objectMapper = new ObjectMapper();
        //将JSON字符串转换成Map集合  inputCode 不是类的属性
        Map<String, String> map = objectMapper.readValue(inputStream, Map.class);

        String username = map.get("username");
        String password = map.get("password");
        String inputCode = map.get("inputCode");

        PrintWriter writer = response.getWriter();
        HttpSession session = request.getSession();
        String code = (String) session.getAttribute("code");
        //先比较验证码
        if (!inputCode.isEmpty() && inputCode.equalsIgnoreCase(code)) {
            ManagerService managerService = new ManagerServiceImpl();
            Manager manager = managerService.login(username, password);
            //将登陆的管理员信息存储在session作用域
            session.setAttribute("manager", manager);

            if (manager == null) {
                writer.print("0");
            } else {
                writer.print("1");
            }
        } else {
            //验证码错误
            writer.print("3");
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
